package com.arpa.wms.controller;

import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.cache.ShipmentCache;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.vo.TreeData;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.cache.GoodsTypeCache;
import com.arpa.wms.domain.entity.GoodsType;
import com.arpa.wms.domain.vo.GoodsTypeVOList;
import com.arpa.wms.service.IGoodsService;
import com.arpa.wms.service.IGoodsTypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

import static com.arpa.wms.domain.consts.NumConst.NUM_ONE;
import static com.arpa.wms.domain.consts.NumConst.NUM_ZERO;

/**
 * @author: Allen chen
 * @Date 2020/8/15
 * @Description:
 */
@Api(tags = "商品类别")
@RestController
@RequestMapping(value = "goodsType",produces = "application/json;charset=UTF-8")
@Log4j2
public class GoodsTypeController {

    private final ShipmentCache shipmentCache;

    private final IGoodsTypeService iGoodsTypeService;

    private final GoodsTypeCache goodsTypeCache;

    private final IGoodsService iGoodsService;

    public GoodsTypeController(
            IGoodsTypeService iGoodsTypeService,
                               GoodsTypeCache goodsTypeCache,
                                ShipmentCache shipmentCache,
                               IGoodsService iGoodsService) {
        this.iGoodsTypeService = iGoodsTypeService;
        this.goodsTypeCache = goodsTypeCache;
        this.shipmentCache = shipmentCache;
        this.iGoodsService = iGoodsService;
    }

    @ApiOperation(value = "添加商品类别 ", notes = "添加 商品类别 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping
    public Result create(@Valid @RequestBody GoodsType dto, HttpServletRequest request){
        try {
            dto.setGroupCode(UserUtil.getBranchCode());
            iGoodsTypeService.save(dto);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取类别详情", notes = "获取类别详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "单位code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = GoodsType.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result detail(@PathVariable String code, HttpServletRequest request){
        try {
            if("0".equals(code)){
                GoodsType res = new GoodsType();
                res.setCode("0");
                res.setName("全部");
                res.setLevel(0);
                return Result.ok().data(res);
            }
            GoodsType type = new GoodsType();
            type.setCode(code);
            GoodsType one = iGoodsTypeService.getOne(new QueryWrapper<GoodsType>().lambda().eq(GoodsType::getCode, code));
            one.setParentName(goodsTypeCache.translate(one.getParentCode()));
            one.setShipmentName(shipmentCache.translate(one.getShipmentCode()));
            return Result.ok().data(one);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "修改类别", notes = "修改类别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping
    public Result update(@RequestBody GoodsType goodsType,HttpServletRequest request){
        if(StrUtil.isBlank(goodsType.getCode())){
            return Result.error("code不能为空");
        }
        try{
            iGoodsTypeService.updateByCode(goodsType);
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除类别", notes = "删除类别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/delete")
    public Result delete(GoodsType goodsType,HttpServletRequest request){

        if(StrUtil.isBlank(goodsType.getCode())){
            return Result.error("code不能为空");
        }
        try{
            GoodsType del = new GoodsType();
            del.setCode(goodsType.getCode());
            del.setDeleted(1);
            iGoodsTypeService.delGoodsTypeWithChild(goodsType);
            goodsTypeCache.flushCache(goodsType.getCode());
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }



    @ApiOperation(value = "获取货主商品分类", notes = "获取货主商品分类列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @GetMapping(value = "/findByShipmentCode")
    public Result findByShipmentCode(String shipmentCode, HttpServletRequest request) {
        try {
            if(StrUtil.isBlank(shipmentCode)){
                return Result.ok();
            }

            List<TreeData> treeData = iGoodsTypeService.findByShipmentCode(shipmentCode);
            return Result.ok().data(treeData);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    @ApiOperation(value = "获取 商品类别 列表", notes = "获取 商品类别 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = GoodsTypeVOList.class))
    @NeedLogin
    @GetMapping()
    public Result list(GoodsType goodsType, HttpServletRequest request) {
        try {
            GoodsTypeVOList goodsTypeVO = iGoodsTypeService.queryList(goodsType);
            return Result.ok().data(goodsTypeVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "删除 商品类型", notes = "删除 商品类型", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "商品类型code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @DeleteMapping(value = "/{code}")
    public Result delete(@PathVariable String code, HttpServletRequest request) {
        try {
            iGoodsTypeService.removeByCode(code);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "判断商品分类能否新增子节点", notes = "判断商品分类能否新增子节点", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "商品类型code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @GetMapping(value = "/canAdd/{code}")
    public Result canAdd(@PathVariable String code, @RequestParam("type") Integer type, HttpServletRequest request) {
        try {
            GoodsType res = new GoodsType();
            if (type.equals(NUM_ZERO)) {
                int countByTypeCode = iGoodsService.countByTypeCode(code);
                res.setCanAdd(countByTypeCode <= NUM_ZERO.intValue());
            }
            if (type.equals(NUM_ONE)) {
                int countChildren = iGoodsTypeService.countChildren(code);
                res.setCanAdd(countChildren <= NUM_ZERO.intValue());
            }
            return Result.ok().data(res);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

}
